<?php

namespace app\common\model;

use app\store\model\Setting as SettingModel;
use think\Request;

/**
 * 用户模型类
 * Class User
 * @package app\common\model
 */
class User extends BaseModel
{
    protected $name = 'user';

    // 性别
    private $gender = ['未知', '男', '女'];

    /**
     * 关联收货地址表
     * @return \think\model\relation\HasMany
     */
    public function address()
    {
        return $this->hasMany('UserAddress');
    }

    /**
     * 关联收货地址表 (默认地址)
     * @return \think\model\relation\BelongsTo
     */
    public function addressDefault()
    {
        return $this->belongsTo('UserAddress', 'address_id');
    }

    /**
     * 显示性别
     * @param $value
     * @return mixed
     */
    public function getGenderAttr($value)
    {
        return $this->gender[$value];
    }

    /**
     * 获取用户列表
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList( $where = array() , $wherenew = '' )
    {
        $request = Request::instance();
        return $this->where($where)->where($wherenew)->order(['create_time' => 'desc'])
            ->paginate(15, false, ['query' => $request->request()]);
    }

    /**
     * 获取用户信息
     * @param $where
     * @return null|static
     * @throws \think\exception\DbException
     */
    public static function detail($where)
    {
        return self::get($where, ['address', 'addressDefault']);
    }
    
    /**
     * 加密
     * @param type $password
     * @return string
     */
    public function passmd5( $password ){
        if( !$password ) return '';
        return md5($password . 'csk#16.%you');
    }
	
	/**
	 * 根据分销规则创建数据
	 */
	public function builddistribution( $ordersn ) {
		if( !$ordersn ) return false;
		$data = SettingModel::getItem('distribution');
		//print_r( $data );die;
		$order = db("member_cart_order")->alias('co')->join("yoshop_user u",'u.user_id = co.user_id')
				 ->field("co.*,u.parent_id,u.is_open_cart,u.share_code,u.service_num as user_service_num,u.identity")->where(['co.ordersn' => $ordersn])->find();
		$identity = $order['identity'];
		//判断用户是否已开通会员卡 如果没有开通则开通
		$save_data = ['is_open_cart' => 1,'open_cart_time' => time(), 'service_num' => $order['service_num'] + $order['user_service_num']];
		//增加推荐码
		if( !$order['share_code'] ) {
			
		}
		if( $order['is_open_cart'] <= 0 ) {
			$save_data['identity'] = 10;
			$cart_sn = db("user")->order("cart_sn DESC")->value("cart_sn");
			$save_data['cart_sn'] = ( $cart_sn ? $cart_sn : 10000 )  + rand(20 , 50);
			$order['identity'] = 10;
		} else { //重复购买 触发感恩奖
			$user_data = [];
			$this->thanksgivingReward($order['parent_id'], $user_data,1 ,$data['repeat_buy']['level']);
			foreach( $user_data as $v1 ) {
				if( isset($data['repeat_buy']['price']) && $data['repeat_buy']['price'] > 0 ) {
					db("member_cart_order_distribution")->insert([
						'user_id' => $v1,
						'type' => 3,
						'status' => 1,
						'price' => $data['repeat_buy']['price'],
						'ordersn' => $order['ordersn'],
						'member_cart_order_id' => $order['id'],
						'create_time' => time()
					]);
					//写入积分
					//写入用户交易日志
					db("user_integral_log")->insert([
						'user_id' => $v1,
						'num' => $data['repeat_buy']['price'],
						'type' => 1,
						'content' => '您的团队成员购买会员卡，您获得复购奖【'.$data['repeat_buy']['price'].'】积分',
						'create_time' => time()
					]);
					$fg_user_info = db("user")->where(['user_id' => $v1])->find();
					db("user")->where(['user_id' => $v1])->update(['integral' => $fg_user_info['integral'] + $data['repeat_buy']['price'],'total_integral' => $fg_user_info['total_integral'] + $data['repeat_buy']['price']]);
				}
			}
			$save_data['tx_total_price'] = 0;
			db("user")->where(['user_id' => $order['user_id']])->update($save_data);
          	return false;
		}
		
		$save_data['tx_total_price'] = 0;
		db("user")->where(['user_id' => $order['user_id']])->update($save_data);
		//写入开卡用户销售
		$this->writeSales( $order['user_id'] , $order['price'] , 1 );
		//判断是否开启分销
		if( $data['open'] != 1 ) return;
		//获得直推用户
		$direct_user_info = db("user")->where(['user_id' => $order['parent_id']])->find();
		if( !$direct_user_info ) return;
		//写入直推开卡用户销售
		$this->writeSales( $direct_user_info['user_id'] , $order['price'] , 1 );
		$this->adddistribution( $direct_user_info , $order , $data , 1 , $order['identity'] );
		//获得间推用户
		$indirect_user_info = db("user")->where(['user_id' => $direct_user_info['parent_id']])->find();
		//不存在的时候或者同级别的时候直接返回
		if( !$indirect_user_info ) return;
		//写入间推开卡用户销售
		$this->writeSales( $indirect_user_info['user_id'] , $order['price'] , 1 );
		$isoperation = false;
		//只拦截总经理级别
		if( $indirect_user_info['identity'] >= $direct_user_info['identity'] && $direct_user_info['identity'] < 30 ){
			$isoperation = true;
		}
		/*if( ( $indirect_user_info['identity'] > $direct_user_info['identity'] && $indirect_user_info['identity'] >= 20 ) || ( $indirect_user_info['identity'] == 10 && $indirect_user_info['identity'] >= $direct_user_info['identity'] ) ) {
			$isoperation = true;
		}*/
		$this->adddistribution( $indirect_user_info , $order , $data , 2 , $direct_user_info['identity'] , $isoperation);
		
		//团长奖励
		$this->colonelReward($order['user_id'],$order['id']);
	}
	
	/**
	 * 感恩奖
	 */
	private function thanksgivingReward($id , &$data , $level , $repeat_buy_level) {
		if( $id && $level  <=  $repeat_buy_level ) {
			$info = db("user")->where(['user_id' => $id])->find();
			if( $info ) {
				//向上查找10位开通会员的用户
				if( $info['is_open_cart'] == 1 ){
					$data[] = $info['user_id'];
					$level = $level + 1;
				}
				$this->thanksgivingReward( $info['parent_id'] , $data , $level , $repeat_buy_level);
			}
		}
	}
	
	/**
	 * 增加分销规则
	 */
	private function adddistribution( $user_info , $order , $data , $type = 1 , $parent_ident = 0 , $isoperation = true) {
		$fenxiao_rule = [0 => 'member', 10 => 'salesman' , 20 => 'salesmanager' , 30 => 'generalmanager'];
		//根据不同的角色执行不同的操作
		$data_value = [];
		$user_direct_total = db("user")->where(['parent_id' => $user_info['user_id']])->field("user_id")->select()->toArray();
		$direct_user_ids = array_column( $user_direct_total , 'user_id' );
		if( $direct_user_ids ) {
			$order_direct_total = db("member_cart_order")->where(['user_id' => ['IN' , implode(",",$direct_user_ids)],'status' => 1])->group("user_id")->field("user_id")->select()->toArray();
		} else {
			$order_direct_total = [];
		}
		switch( $fenxiao_rule[$user_info['identity']] ) {
			/*case 'member' : //普通会员
				$fx_config = SettingModel::getItem('distribution');
				$data_value = $type == 1 ? $data['member']['direct'] : $data['member']['indirect'];
				if( !isset( $fx_config['member']['open'] ) || !$fx_config['member']['open'] ) return false;
			break;*/
			case 'salesman' : //业务员
			$data_value = $type == 1 ? $data['salesman']['direct'] : $data['salesman']['indirect'];
			//判断是否升级
			if( $order_direct_total ) {
				if( count($order_direct_total) >= $data['salesmanager']['direct_upgrade'] ) {
					db("user")->where(['user_id' => $user_info['user_id']])->update(['identity' => 20]);
				}
			}
			break;
			case 'salesmanager' : //销售经理
			if( $type == 1 ) {
				$data_value = $data['salesmanager']['direct'];
			} else if( $parent_ident == 10 ){ //判断间推的是否是业务员
				$data_value = $data['salesmanager']['teammembers'];
			} else if( $parent_ident == 20 ){ //判断间推的是否是销售经理
				$data_value = $data['salesmanager']['indirect'];
			}
			//判断是否升级
			if( $order_direct_total ) {
				$user_ids = array_column( $order_direct_total , 'user_id' );
				$inrect_user_data = db("user")->where("parent_id IN (".implode("," , $user_ids).")")->field('user_id')->select()->toArray();
				if( $inrect_user_data ) {
					$user_ids = array_column( $inrect_user_data , 'user_id' );
					//获得二级团队的直推单数
					$total_data = db("member_cart_order")->where("user_id IN (".implode("," , $user_ids).") AND status = 1")->group("user_id")->field("user_id")->select()->toArray();
					$total_data = $total_data ? count($total_data) : 0;
					if( $total_data ) {
						if( count($order_direct_total) >= $data['generalmanager']['my_direct_num'] && $total_data >= $data['generalmanager']['team_direct_num'] ) {
							db("user")->where(['user_id' => $user_info['user_id']])->update(['identity' => 30]);
						}
					}
				}
			}
			
			break;
			case 'generalmanager' : //总经理
			if( $type == 1 ) {
				$data_value = $data['generalmanager']['direct'];
			} else if( $parent_ident == 10 ){ //判断直推的是否是业务员
				$data_value = $data['generalmanager']['teammembers'];
			} else if( $parent_ident == 20 ) { //判断直推的否是
				$data_value = $data['generalmanager']['teammanager'];
			}
            //判断是否升级团长
			$item_price = $this->itemPrices($user_info['user_id']);
			$setting_price = isset($data['item']['condition']) && $data['item']['condition'] > 0 ? $data['item']['condition'] * 10000 : 0;
			if( $setting_price > 0 && $item_price >= $setting_price ) {
				db("user")->where(['user_id' => $user_info['user_id']])->update(['is_item' => 1]);
			}
			break;
		}
		if( !$data_value || $isoperation !== true ) return; 
		//判断提成类型
		if( $data_value['type'] == 1 ) {
			$price = $data_value['value'];
		} else {
			$price = round( $order['price'] * $data_value['value'] / 100 , 2 );
		}
		if( $price <= 0 ) return false;
		//添加收益数据
		db("member_cart_order_distribution")->insert([
			'user_id' => $user_info['user_id'],
			'type' => $type,
			'price' => $price,
			'ordersn' => $order['ordersn'],
			'member_cart_order_id' => $order['id'],
			'create_time' => time()
		]);
		//增加积分
		//写入用户交易日志
		db("user_integral_log")->insert([
			'user_id' => $user_info['user_id'],
			'num' => $price,
			'type' => 1,
			'content' => '您的团队成员购买会员卡，您获得'.($type == 1 ? '直推' : '间推').'奖【'.$price.'】积分',
			'create_time' => time()
		]);
		db("user")->where(['user_id' => $user_info['user_id']])->update(['integral' => $user_info['integral'] + $price , 'total_integral' => $user_info['total_integral'] + $price]);
	}
	
	
	/**
	 * 团长提成
	 */
	public function colonelReward( $user_id , $order_id ) {
		if( !$user_id || !$order_id ) return false;
		//获得会员卡订单ID
		$order_info = db("member_cart_order")->where(['id' => $order_id])->find();
		if( !$order_info || $order_info['status'] != 1 ) return false;
		//获得配置
		$config = SettingModel::getItem('distribution');
		$item_config = $config['item'];
		//获得用户上级的3个团长
		$user_info = db("user")->where(['user_id' => $user_id])->find();
		$select_user_id = $user_info['parent_id'];
		$select_level_data = $item_config['level'];//获得团长层级 3
		$user_item_data = [];
		if( $user_info['is_item'] == 1 ) {
			$select_level_data = $select_level_data - 1;
			$user_item_data[] = $user_info['user_id'];
		}
		if( $select_level_data > 0 ) {
			for( $i = 0; $i <= 10000000; $i++ ) {
				$user_info = db("user")->where(['user_id' => $select_user_id])->find();
				if( $user_info ) {
					if( $user_info['is_item'] == 1 ) {
						$user_item_data[] = $user_info['user_id'];
					}
					if( $user_info['parent_id'] <= 0 ) break;
					$select_user_id = $user_info['parent_id'];
					//判断是否是已经达到了3位团长 如果达到则直接跳出查询操作
					if( count( $user_item_data ) >= $select_level_data ) {
						break;
					}
				} else {
					break;
				}
			}
		}
		//判断是否有团长  如果没有则直接结束
		if( count( $user_item_data ) <= 0 ) return false;
		$proportion = explode("," , $item_config['proportion']);
		foreach( $proportion as $k => $v ) {
			//判断后端是否设置了团长的提成比例
			if( isset( $user_item_data[$k] ) && $user_item_data[$k] > 0 ) {
				$tc_money = round( $order_info['price'] * $v / 100 );
				$item_user_id = $user_item_data[$k];
				//获得团长信息
				$item_user_info = db("user")->where(['user_id' => $item_user_id])->find();
				//写入分销日志
				db("member_cart_order_distribution")->insert([
					'user_id' => $item_user_id,
					'type' => 4,
					'status' => 1,
					'price' => $tc_money,
					'ordersn' => $order_info['ordersn'],
					'member_cart_order_id' => $order_info['id'],
					'create_time' => time()
				]);
				//写入系统消息
				db("system_message")->insert([
					'user_id' => $item_user_id,
					'type' => 1,
					'content' => '您的团队成员购买会员卡，您获得团长提成【'.$tc_money.'】积分',
					'create_time' => time()
				]);
				//团长用户增加金额
				db("user")->where(['user_id' => $item_user_id])->update(['integral' => $item_user_info['integral'] + $tc_money , 'total_integral' => $item_user_info['total_integral'] + $tc_money]);
				//写入用户交易日志
				db("user_integral_log")->insert([
					'user_id' => $item_user_id,
					'num' => $tc_money,
					'type' => 1,
					'content' => '您的团队成员购买会员卡，您获得团长提成【'.$tc_money.'】积分',
					'create_time' => time()
				]);
			}
		}
	}
	
	/**
	 * 获得团队的总销售额
	 */
	public function itemPrices($user_id) {
		$user_data = [];
		$total_price = 0;
		$this->friend( $user_id , $user_data );
		if( $user_data ) {
			$total_price = db("member_cart_order")->where(['user_id' => ['IN' , implode(',' , $user_data)],'status' => 1])->sum('price');
		}
		return $total_price;
	}
	
	private function friend($id , &$user_data) {
		if( !$id ) return '';
		$user = db("user")->where(['parent_id' => $id])->field("user_id as id,nickname as name,identity,parent_id as pId,is_item")->select()->toArray();
		if( $user ) {
			foreach( $user as $k => $v) {
				$user_data[] = $v['id'];
				$list = $this->friend( $v['id'] , $user_data );
			}
		}
	}
	
	//写入延迟的订单数据
	public function delay($order_id) {
		if( $order_id <= 0 ) return false;
		$config = SettingModel::getItem('store');
		$order_info = db("member_cart_order")->where(['id' => $order_id])->find();
		if( $order_info && $order_info['status'] == 1 ) {
			$time = isset( $config['yc_online_open_user_time'] ) && $config['yc_online_open_user_time']>0 ? $config['yc_online_open_user_time'] : 0;
			db("member_cart_order_delay")->insert([
				'ordersn' => $order_info['ordersn'],
				'user_id' => $order_info['user_id'],
				'order_id' => $order_info['id'],
				'create_time' => $order_info['create_time'],
				'hour_data' => $time,
				'open_time' => $order_info['create_time'] + $time * 3600,
			]);
		}
	}
	
	//写入销售额
	public function writeSales( $user_id , $price , $type = 1 , $name = '') {
		if( !$user_id || !$price ) return false;
		$user_info = db("user")->where(['user_id' => $user_id])->find();
		if( !$user_info ) return false;
		db("user")->where(['user_id' => $user_id])->update(['sales_achievement' => $user_info['sales_achievement'] + $price]);
		db('user_sales_log')->insert([
			'user_id' => $user_id,
			'content' => ( $type == 1 ? '自己' : ( $type == 2 ? '直推会员【'.$name.'】' : '间推会员【'.$name.'】' ) ) .'购买会员卡获得【'.$price.'】积分业绩',
			'create_time' => time()
		]);
	}
	
	//普通用户推荐奖励
	public function ordinaryuserRec( $user_id ){
		if( !$user_id ) return false;
		$user_info = db("user")->where(['user_id' => $user_id])->find();
		if( !$user_info || !$user_info['parent_id'] ) return false;
		//获得直推用户
		$info = db("user")->where(['user_id' => $user_info['parent_id']])->find();
		$fx_config = SettingModel::getItem('distribution');
		$trade_config = SettingModel::getItem('trade');
		if( $info ) {
			if( $info['is_open_cart'] == 0 ) {
				$data_value = $fx_config['member']['direct']['value'];
				if( $data_value && $data_value > 0 && ( !$trade_config['clear']['where'] || $info['integral'] < $trade_config['clear']['where'] ) ) {
					$user_integral = $info['integral'] + $data_value;
					$zj_integral = $data_value;
					if( isset( $trade_config['clear']['where'] ) && $trade_config['clear']['where'] && $user_integral > $trade_config['clear']['where'] ) {
						$zj_integral = $data_value - ( $user_integral - $trade_config['clear']['where'] );
						$user_integral = $trade_config['clear']['where'];
					}
					//添加收益数据
					db("member_cart_order_distribution")->insert([
						'user_id' => $info['user_id'],
						'type' => 1,
						'price' => $zj_integral,
						'ordersn' => '-',
						'member_cart_order_id' => 0,
						'create_time' => time()
					]);
					//增加积分
					//写入用户交易日志
					db("user_integral_log")->insert([
						'user_id' => $info['user_id'],
						'num' => $zj_integral,
						'type' => 1,
						'content' => '推荐用户注册，您获得直推奖【'.$zj_integral.'】积分',
						'create_time' => time()
					]);
					db("user")->where(['user_id' => $info['user_id']])->update(['integral' => $user_integral , 'total_integral' => $info['total_integral'] + $zj_integral]);
				}
			}
			//间推会员
			if( !$info['parent_id'] ) return false;
			$info = db("user")->where(['user_id' => $info['parent_id'] , 'is_open_cart' => 0])->find();
			if( !$info ) return false;
			$data_value = $fx_config['member']['indirect']['value'];
			if( $data_value && $data_value > 0 && ( !$trade_config['clear']['where'] || $info['integral'] < $trade_config['clear']['where'] )) {
				$user_integral = $info['integral'] + $data_value;
				$zj_integral = $data_value;
				if( isset( $trade_config['clear']['where'] ) && $trade_config['clear']['where'] && $user_integral > $trade_config['clear']['where'] ) {
					$zj_integral = $data_value - ( $user_integral - $trade_config['clear']['where'] );
					$user_integral = $trade_config['clear']['where'];
				}
				//添加收益数据
				db("member_cart_order_distribution")->insert([
					'user_id' => $info['user_id'],
					'type' => 2,
					'price' => $zj_integral,
					'ordersn' => '-',
					'member_cart_order_id' => 0,
					'create_time' => time()
				]);
				//增加积分
				//写入用户交易日志
				db("user_integral_log")->insert([
					'user_id' => $info['user_id'],
					'num' => $zj_integral,
					'type' => 1,
					'content' => '推荐用户注册，您获得间推奖【'.$zj_integral.'】积分',
					'create_time' => time()
				]);
				db("user")->where(['user_id' => $info['user_id']])->update(['integral' => $user_integral , 'total_integral' => $info['total_integral'] + $zj_integral]);
			}
		}
	}
	
}
